import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';

const catchUrls = ['m.ctrip.com/', 'm.ctrip.com/html5', 'm.ctrip.com/html5'];

class WebView extends StatefulWidget {
  final String? url;
  final String? statusBarColor;
  final String? title;
  final bool? hideAppBar;
  final bool backForbid;

  const WebView(
      {super.key,
      this.url,
      this.statusBarColor,
      this.title,
      this.hideAppBar,
      this.backForbid = false});

  @override
  State<WebView> createState() => _WebViewState();
}

class _WebViewState extends State<WebView> {
  final webviewReference = FlutterWebviewPlugin();
  late StreamSubscription<String> _onUrlChanged;
  late StreamSubscription<WebViewStateChanged> _onStateChanged;
  late StreamSubscription<WebViewHttpError> _onHttpError;
  bool exiting = false;

  @override
  void initState() {
    super.initState();
    webviewReference.close();
    _onUrlChanged = webviewReference.onUrlChanged.listen((String url) {
      debugPrint(url);
    });

    _onStateChanged =
        webviewReference.onStateChanged.listen((WebViewStateChanged state) {
      switch (state.type) {
        case WebViewState.startLoad:
          debugPrint('加载开始');
          if (_isToMain(state.url) && !exiting) {
            if (widget.backForbid) {
              webviewReference.launch(widget.url!);
            } else {
              Navigator.pop(context);
              exiting = true;
            }
          }
          break;
        case WebViewState.shouldStart:
          debugPrint('马上开始');

          break;
        case WebViewState.finishLoad:
          debugPrint('完成加载');
          break;
        case WebViewState.abortLoad:
          debugPrint('终止加载');
          break;
        default:
          break;
      }
    });

    _onHttpError =
        webviewReference.onHttpError.listen((WebViewHttpError error) {
      debugPrint(error.toString());
    });
  }

  _isToMain(String url) {
    bool contain = false;
    for (var value in catchUrls) {
      if (url.endsWith(value)) {
        debugPrint('吴斌===》 $url');
        debugPrint('吴斌===》 ${url.endsWith(value)}');
        contain = true;
        break;
      }
    }
    return contain;
  }

  @override
  void dispose() {
    _onStateChanged.cancel();
    _onHttpError.cancel();
    _onUrlChanged.cancel();
    webviewReference.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    String statusBarColorStr = widget.statusBarColor ?? 'ffffff';
    Color backButtonColor;
    if (statusBarColorStr == 'ffffff') {
      backButtonColor = Colors.black;
    } else {
      backButtonColor = Colors.white;
    }

    return Scaffold(
      body: Column(
        children: <Widget>[
          _appBar(Color(int.parse('0xff$statusBarColorStr')), backButtonColor),
          Expanded(
              child: WebviewScaffold(
            url: widget.url!,
            withZoom: true,
            withLocalStorage: true,
            // hidden: true,
            // initialChild: Container(
            //   color: Colors.white,
            //   child: const Center(
            //     child: Text('Waiting...'),
            //   ),
            // ),
          ))
        ],
      ),
    );
  }

  _appBar(Color backgroundColor, Color backButtonColor) {
    if (widget.hideAppBar ?? false) {
      return Container(
        color: backgroundColor,
        height: 48,
      );
    }
    return Container(
      color: backgroundColor,
      padding: const EdgeInsets.fromLTRB(0, 40, 0, 10),
      child: FractionallySizedBox(
      widthFactor: 1,
      child: Stack(
        children: <Widget>[
          GestureDetector(
            onTap: (){
              webviewReference.dispose();
              Navigator.pop(context);
            },
            child: Container(
              margin: const EdgeInsets.only(left: 10),
              child: Icon(Icons.close, color: backButtonColor, size: 26),
            ),
          ),
          Positioned(
              child: Center(
            child: Text(
              widget.title ?? '',
              style: TextStyle(color: backButtonColor, fontSize: 20),
            ),
          ))
        ],
      ),
    ),
    );
  }
}
